package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.StrategyQueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import cn.wolfcode.trip.base.util.JasonResult;
import cn.wolfcode.trip.base.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/strategy")
public class StrategyController {

    //注入service对象
    @Autowired
    private IStrategyService strategyService ;
    @Autowired
    private IRegionService regionService ;
    /*
    *新增或者修改的操作
    *
    * */

    @RequestMapping("/saveOrUpdate.do")
    @ResponseBody
    public Object saveOrUpdate(Strategy strategy, MultipartFile img){
        JasonResult jr = new JasonResult();
        //需要判断一下对方有没有上传封面的图片，有的话就将上传文件所得到的路径交给对象中的封面属性
        if (img!=null&&img.getContentType().startsWith("image")&&img.getSize()>0) {
            String url = UploadUtil.upload(img);
            strategy.setCoverUrl(url);
        }
        try {
            //调用service中的方法
            strategyService.saveOrUpdate(strategy);
        } catch (Exception e) {
            e.printStackTrace();
            jr.mark(e.getMessage());
        }
        return jr ;
    }

    /**
     * 大攻略的主页面
     * @param qo
     * @param model
     * @return
     */
    @RequestMapping("/list.do")
    public String list(@ModelAttribute("qo") StrategyQueryObject qo, Model model){
        model.addAttribute("pageInfo",strategyService.query(qo));
        model.addAttribute("regions",regionService.listAll(null));
        return "strategy/list" ;
    }

}
